package com.test.platform.service.Project;

import com.test.platform.dao.ProjectMapper;
import com.test.platform.model.Project;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.io.File;
import java.io.IOException;
import java.util.Map;

@Slf4j
@Service
public class ProjectService {
    
    @Autowired
    private ProjectMapper projectMapper;
    
    @Autowired
    private RestTemplate restTemplate;
    
    private static final String BASE_GITCODE_URL = "https://gitcode.com/%s/%s.git";
    private static final String BASE_RAW_URL = "https://raw.gitcode.com/%s/%s/raw/master/library/oh-package.json5";
    private static final String SAMPLE_RAW_URL = "https://raw.gitcode.com/openharmony-tpc/openharmony_tpc_samples/raw/master/%s/library/oh-package.json5";
    
    public List<Project> getAllProjects() {
        return projectMapper.findAll();
    }
    
    public Project getProjectById(Integer id) {
        return projectMapper.findById(id);
    }
    
    public List<Project> getProjectsByOwner(String owner) {
        return projectMapper.findByOwner(owner);
    }
    
    public List<Project> getProjectsByName(String name) {
        return projectMapper.findByName(name);
    }
    
    public List<Project> getProjectsByOwnerAndName(String owner, String name) {
        return projectMapper.findByOwnerAndName(owner, name);
    }
    
    @Transactional
    public boolean createProject(Project project) {
        return projectMapper.insert(project) > 0;
    }
    
    public boolean updateProject(Project project) {
        return projectMapper.update(project) > 0;
    }
    
    @Transactional
    public boolean deleteById(Integer id) {
        try {
            return projectMapper.deleteById(id) > 0;
        } catch (Exception e) {
            log.error("删除项目失败: id={}", id, e);  // 将 logger 改为 log
            return false;
        }
    }

    @Transactional
    public boolean deleteByIds(List<Integer> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return false;
            }
            return projectMapper.deleteByIds(ids) > 0;
        } catch (Exception e) {
            log.error("批量删除项目失败: ids={}", ids, e);  // 将 logger 改为 log
            return false;
        }
    }
    
    @Transactional
    public void initializeProjectsFromJson() {
        try {
            ObjectMapper mapper = new ObjectMapper();
            
            // 读取主要仓库配置
            File reposFile = new File("src/main/resources/data/repos.json");
            JsonNode reposNode = mapper.readTree(reposFile);
            processRepositories(reposNode.get("repositories"));
            
            // 读取示例仓库配置
            File sampleFile = new File("src/main/resources/data/repos_sample.json");
            JsonNode sampleNode = mapper.readTree(sampleFile);
            processSampleRepositories(sampleNode.get("repositories"));
            
        } catch (IOException e) {
            log.error("初始化项目信息失败", e);
        }
    }
    
    private void processRepositories(JsonNode repositories) {
        if (repositories == null) return;
        
        repositories.forEach(repo -> {
            String owner = repo.get("owner").asText();
            String name = repo.get("name").asText();
            
            Project project = new Project();
            project.setOwner(owner);
            project.setName(name);
            
            if ("openharmony-sig".equals(owner) || "openharmony-tpc".equals(owner)) {
                project.setGitUrl(String.format(BASE_GITCODE_URL, owner, name));
                String description = fetchDescription(String.format(BASE_RAW_URL, owner, name));
                project.setDescription(description);
            }
            
            try {
                if (projectMapper.findByOwnerAndName(owner, name).isEmpty()) {
                    projectMapper.insert(project);
                    log.info("成功创建项目: {}/{}", owner, name);
                } else {
                    projectMapper.update(project);
                    log.info("成功更新项目: {}/{}", owner, name);
                }
            } catch (Exception e) {
                log.error("处理项目失败: {}/{}", owner, name, e);
            }
        });
    }
    
    private void processSampleRepositories(JsonNode repositories) {
        if (repositories == null) return;
        
        repositories.forEach(repo -> {
            String name = repo.get("name").asText();
            
            Project project = new Project();
            project.setOwner("openharmony_tpc_sample");
            project.setName(name);
            project.setGitUrl(String.format("https://gitcode.com/openharmony-tpc/openharmony_tpc_samples/tree/master/%s.git", name));
            
            String description = fetchDescription(String.format(SAMPLE_RAW_URL, name));
            project.setDescription(description);
            
            try {
                if (projectMapper.findByOwnerAndName("openharmony_tpc_sample", name).isEmpty()) {
                    projectMapper.insert(project);
                    log.info("成功创建示例项目: {}", name);
                } else {
                    projectMapper.update(project);
                    log.info("成功更新示例项目: {}", name);
                }
            } catch (Exception e) {
                log.error("处理示例项目失败: {}", name, e);
            }
        });
    }
    
    private String fetchDescription(String url) {
        try {
            String response = restTemplate.getForObject(url, String.class);
            if (response != null) {
                // 简单解析json5格式，获取description字段
                int descStart = response.indexOf("\"description\":");
                if (descStart != -1) {
                    int valueStart = response.indexOf("\"", descStart + 13) + 1;
                    int valueEnd = response.indexOf("\"", valueStart);
                    if (valueStart != -1 && valueEnd != -1) {
                        return response.substring(valueStart, valueEnd);
                    }
                }
            }
            log.warn("无法获取描述信息: {}", url);
            return "暂无描述";
        } catch (Exception e) {
            log.error("获取描述信息失败: {}", url, e);
            return "暂无描述";
        }
    }
    
    @Transactional
    public void updateProjectsFromRepos(List<Map<String, String>> repos) {
        for (Map<String, String> repo : repos) {
            try {
                String owner = repo.get("owner");
                String name = repo.get("name");
                
                // 检查项目是否存在
                List<Project> existingProjects = projectMapper.findByOwnerAndName(owner, name);
                if (existingProjects.isEmpty()) {
                    // 创建新项目
                    Project project = new Project();
                    project.setOwner(owner);
                    project.setName(name);
                    setProjectProperties(project, repo);
                    projectMapper.insert(project);
                    log.info("创建新项目: {}/{}", owner, name);
                } else {
                    // 更新现有项目
                    Project project = existingProjects.get(0);
                    setProjectProperties(project, repo);
                    projectMapper.update(project);
                    log.info("更新现有项目: {}/{}", owner, name);
                }
            } catch (Exception e) {
                log.error("处理项目失败: {}/{}", repo.get("owner"), repo.get("name"), e);
            }
        }
    }

    private void setProjectProperties(Project project, Map<String, String> repo) {
        String owner = repo.get("owner");
        String name = repo.get("name");
        
        // 设置 Git URL
        if ("openharmony-sig".equals(owner) || "openharmony-tpc".equals(owner)) {
            String gitUrl = String.format(BASE_GITCODE_URL, owner, name);
            project.setGitUrl(gitUrl);
            String description = fetchDescription(String.format(BASE_RAW_URL, owner, name));
            project.setDescription(description);
        } else if ("openharmony_tpc_sample".equals(owner)) {
            String gitUrl = String.format("https://gitcode.com/openharmony-tpc/openharmony_tpc_samples/tree/master/%s.git", name);
            project.setGitUrl(gitUrl);
            String description = fetchDescription(String.format(SAMPLE_RAW_URL, name));
            project.setDescription(description);
        }
        
        // 如果没有设置描述，设置默认值
        if (project.getDescription() == null || project.getDescription().isEmpty()) {
            project.setDescription("暂无描述");
        }
    }
    
    
}